package com.just.dom4j;

import java.io.FileWriter;
import java.io.IOException;
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

/**
 * 将xml文档写入文件
 */
public class WriteXML {
    public static void main(String[] args) throws IOException {
        Document document=CreateXML.createDocument();
        write1(document);
        System.out.println("第一种完成");
        write2(document);
    }
    /**
     * 第一种，直接写入
     *
     * @param document
     */
    public static void write1(Document document) {
        try {
            FileWriter out = new FileWriter("demo2.xml");
            document.write(out);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 如果你想改变输出的格式，比如美观的格式（含缩进）和压缩的格式（不含缩进），可以使用XMLWriter类。
     * @param document document
     * @throws IOException
     */
    public static void write2(Document document) throws IOException {
        // lets write to a file
        XMLWriter writer = new XMLWriter(new FileWriter("demo3.xml"));
        writer.write(document);
        writer.close();

        // Pretty print the document to System.out  有缩进，界面友好
        OutputFormat format = OutputFormat.createPrettyPrint();
        writer = new XMLWriter(System.out, format);
        writer.write(document);
        writer.close();

        // Compact format to System.out  无缩进，界面不友好
        format = OutputFormat.createCompactFormat();
        writer = new XMLWriter(System.out, format);
        writer.write(document);
        writer.close();
    }
}
